from typing import List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        result = []
        queue = []
        if not root:
            return result
        queue.append(root)
        while len(queue) > 0:
            result.append([node.val for node in queue])
            temp = []
            for node in queue:
                if node.left:
                    temp.append(node.left)
                if node.right:
                    temp.append(node.right)
            queue = temp
        return [s[-1] for s in result]


if __name__ == '__main__':
    root = TreeNode(3)
    root.left = TreeNode(9)
    root.left.left = TreeNode(10)
    root.right = TreeNode(20)
    root.right.left = TreeNode(15)
    root.right.right = TreeNode(7)

    x = Solution()
    print(x.levelOrder(root))
